local lspconfig = require("lspconfig")
local server = require("plugin.plugins.lsp.set_lsp_server")
-- 管理 lsp server
server.set_lsp_server(lspconfig)

local function hover_highlight_word(client_id)
  -- https://neovim.io/doc/user/lsp.html
  local client = vim.lsp.get_client_by_id(client_id)
  -- vim.notify(client.name, vim.log.levels.INFO, {})
  if client.server_capabilities.documentHighlightProvider then
    -- 光标所在的字符词语高亮相同的单词， 可以用插件： "RRethy/vim-illuminate",
    vim.api.nvim_exec(
      [[
          augroup lsp_document_highlight
            autocmd! * <buffer>
            autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
            autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
          augroup END
        ]],
      false
    )
  end
end

-- =================================================================
local keymap = vim.keymap
local diagnostic = vim.diagnostic

-- 以浮窗形式显示错误
keymap.set("n", "go", diagnostic.open_float)
keymap.set("n", "gp", diagnostic.goto_prev)
keymap.set("n", "gn", diagnostic.goto_next)
keymap.set("n", "gs", diagnostic.setloclist)

local bind_key = require("plugin.plugins.lsp.bind_key")

vim.api.nvim_create_autocmd("LspAttach", {
  group = vim.api.nvim_create_augroup("UserLspConfig", {}),
  callback = function(ev)
    local bufopts = { buffer = ev.buf }

    -- 快捷键绑定
    bind_key.bind_keymap(bufopts)

    -- 快捷键格式化
    keymap.set("n", "<C-f>", function()
      -- vim.notify(client.name .. ", Formated", vim.log.levels.INFO, {})
      --  注意这里 async = true
      vim.lsp.buf.format({ async = true })
    end, bufopts)
    -- 插件 guard 的格式化
    keymap.set("n", "<Leader>ff", "<cmd>GuardFmt<CR>", bufopts)

    -- 保存格式化
    vim.api.nvim_create_autocmd("BufWritePre", {
      group = vim.api.nvim_create_augroup("LspFormatting", { clear = true }),
      buffer = ev.buf,
      callback = function()
        -- vim.notify(client.name .. " , Saved format!", vim.log.levels.INFO, {})
        -- vim.notify(string.format("%s%s", client.name, ", Saved format!"), vim.log.levels.INFO, {})

        --  注意这里 async = false,否则会不断有问题
        vim.lsp.buf.format({ async = false })
      end,
    })

    -- 高亮鼠标悬浮的相关的所有词语
    hover_highlight_word(ev.data.client_id)
  end,
})

return {}
